﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aierp.Controllers;
using Aierp.Entities;
using Aierp.Repository.Models;
using Aierp.SystemEntities.System;
using Aierp.SystemRepository.Models;
using Aierp.Utility;
using Aierp.Utility.Data;

namespace Aierp.Repository.Implements
{
    public class NavigationRepository : DbInstance
    {
        public int Add(Sys_Navigations item)
        {
            var result = this.Insert<Sys_Navigations>(item, c => c.NavTitle == item.NavTitle);
            return result.Item1 < 0 ? result.Item1 : result.Item2.KeyId;
        }

        public Sys_Navigations Find(string key)
        {
            return this.FindBy<Sys_Navigations>(c => c.NavTitle == key);
        }

        public List<Sys_Navigations> FindAll()
        {
            return this.Find<Sys_Navigations>();
        }

        public Sys_Navigations FindById(int id)
        {
            return this.FindBy<Sys_Navigations>(c => c.KeyId == id);
        }

        public string GetList(int limit, int offset, string filter, string sortOrder)
        {
            if (!string.IsNullOrEmpty(filter))
            {
                return this.GetPageList<Sys_Navigations, object>(limit, offset, c => c.ParentID == int.Parse(filter),
                    c => c.Sortnum, sortOrder);
            }
            return this.GetPageList<Sys_Navigations, object>(limit, offset, null, c => c.Sortnum, sortOrder);
        }

        public int Remove(int key)
        {
            //要判断角色在Sys_UserRoles表中是否已经被使用，已经使用的角色不能删除
            //var role = this.FindBy<Sys_UserRoles>(c => c.RoleID == key);
            //if (role != null) return -8;

            return this.Delete<Sys_Navigations>(key);
        }

        public int Update(Sys_Navigations item)
        {
            //先检查是否存在
            var entity = this.FindById(item.KeyId);
            if (entity == null) return -9;
            //检查是否重名
            var d = this.FindAll().Where(c => c.NavTitle == item.NavTitle).ToList();
            //if(d>1) return -2;
            foreach (var s in d)
            {
                if (s.KeyId != item.KeyId)
                {
                    return -2;
                }
            }

            ////更新
            Db.TrackEntity(item); //在上下文中跟踪实体
            //if (entity.RoleName != "管理员") entity.RoleName = item.RoleName;//要判断角色是否为"管理员"，管理员角色名称不能更新
            entity.Sortnum = item.Sortnum;
            entity.NavTitle = item.NavTitle;
            entity.NavTag = item.NavTag;
            entity.Linkurl = item.Linkurl;

            entity.IsVisible = item.IsVisible;
            entity.iconCls = item.iconCls;
            entity.ParentID = item.ParentID;

            return Db.Update(entity); //这时只会更新被修改的字段
        }

        public ConcurrentDictionary<string, string> GetClientsDataJson(int menuId, Sys_Users currentUser)
        {

            var list = this.FindAll().Where(c => c.IsVisible);
            if (!currentUser.IsAdmin)
            {
                var currentRole = 0;
                var d = FindBy<Sys_UserRoles>(c => c.UserID == currentUser.KeyId);
                if (d != null)
                {
                    currentRole = d.RoleID;

                    var sql =
                        string.Format(
                            "select s.* FROM [Cup2017].[dbo].[Sys_Navigations] s left join Sys_RoleNavBtns r on s.KeyId=r.NavId where r.RoleId = {0} ",
                            currentRole);
                    list = Db.SqlQuery<Sys_Navigations>(sql);
                    list = list.Where(c => c.IsVisible).ToList();
                }
                else
                {
                    return null;
                }
            }


            var menuList = new List<MenuModel>();

            foreach (var item in list.Where(it => it.ParentID == menuId))
            {
                var menuModel = new MenuModel();
                menuModel.Id = item.KeyId;
                menuModel.Name = item.NavTitle;
                menuModel.Icon = item.iconCls;
                menuModel.SortCode = item.Sortnum;

                menuModel.ChildNodes =
                    list.Where(c => c.ParentID == item.KeyId)
                        .Select(
                            c =>
                                new ChildNodes
                                {
                                    Id = c.KeyId,
                                    Name = c.NavTitle,
                                    UrlAddress = c.Linkurl,
                                    SortCode = c.Sortnum
                                })
                        .OrderBy(c => c.SortCode).ToList();
                menuList.Add(menuModel);
            }
            menuList = menuList.OrderBy(c => c.SortCode).ToList();
            var info = new ConcurrentDictionary<string, string>();
            info.TryAdd("authorizeMenu", menuList.ToJson());
            return info;
        }

        /// <summary>
        /// 更新html版本号
        /// </summary>
        /// <returns></returns>
        public int UpdateVersion()
        {
            //先检查是否存在
            var entity = this.FindBy<Sys_Config>(c => c.ConfigName == "HtmlVersion");

            if (entity == null) return -2;

            ////更新
            Db.TrackEntity(entity); //在上下文中跟踪实体
            entity.ConfigValue += 1;
            return Db.Update(entity); //这时只会更新被修改的字段
        }

        /// <summary>
        /// 查询最新的html版本号
        /// </summary>
        /// <returns></returns>
        public int FindHtmlVersion()
        {
            //先检查是否存在
            var entity = this.FindBy<Sys_Config>(c => c.ConfigName == "HtmlVersion");
            if (entity == null) return -2;
            return entity.ConfigValue;
        }
    }
}
